package application;

import event.KeyboardEvent;
import game.Game;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;

import parameters.Vec2f;

public class ServerHandler implements Runnable{
	public static final String configFile = "res/config.ini";
	
	private Thread thread;
	private Game game;
	
	private String host;
	private int port;
	
	private int id; //0 or 1 - Defines index of platform u r playing for!
		
	private Socket connection;
	
	private boolean running;

	public ServerHandler(Game game){
		this.game = game;
		loadConfiguration();
		
		thread = new Thread(this, "ServerHandling Thread");
		System.out.println("[i] Created " + thread.getName());
		
		running = true;
		thread.start();
	}
	
	@Override
	public void run() {
	    try {
	    	InetAddress address = InetAddress.getByName(host);
			connection = new Socket(address, port);
			
			System.out.println("[i] Successfuly connected to " + host + ":" + port);
		} catch (IOException e) {
			this.running = false;
			System.out.println("[e] Connection refused!");
		}
	    
		/*while(running){
			//prijme packet a switchne prvni integer v byte array
			
			int something = 1;;
			switch(something){
				case Packet.PACKET_ID_HELLO:
					this.id = something;
				break;
				
				case Packet.PACKET_ID_PLATFORM:
					//set opponents platform position
				break;
				
				case Packet.PACKET_ID_BALL:
					//set ball position
				break;

				case Packet.PACKET_ID_BLOCK_HIT:
					//hit the block on X,Y
				break;
				
				case Packet.PACKET_ID_MAP:
					//load map
				break;
			}
		}*/
	}
	
	private void loadConfiguration(){
		try (BufferedReader br = new BufferedReader(new FileReader(configFile))){
 
			String sCurrentLine;
 
			while ((sCurrentLine = br.readLine()) != null) {
				String[] tmp = sCurrentLine.split(" ");
				
				switch(tmp[0]){
					case	"ip":
						this.host = tmp[1];
					break;
					
					case	"port":
						this.port = Integer.parseInt(tmp[1]);
					break;
				}
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	public void stop(){
		running = false;
	}

}
